package com.itheima.health.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.itheima.health.common.RedisConst;
import com.itheima.health.common.RocketMqConst;
import com.itheima.health.entity.SmsTask;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;


/**
 * 短信服务实现类
 */
@DubboService
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    private IAcsClient acsClient = new DefaultAcsClient(DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>"));

    @Override
    public void sendValidateCode(String type, String telephone , Integer countSend) {
        log.info("[短信验证码发送]type:{},telephone:{}", type, telephone);

        if (countSend > 8) {
            throw new BusinessRuntimeException("操作过于频繁");
        }

        SmsTask smsTask = new SmsTask(type, telephone, countSend);

        rocketMQTemplate.convertAndSend(RocketMqConst.TOPIC_SMS_SEND, smsTask);

        log.info("[短信验证码放入队列]data:{}", smsTask);

        /////////////////////下面代码由阿里云代码模板生成//////////////////

//        // 这里无需真的将短信发送出去，测试过程中，我们直接在日志中查看打印的验证码即可
//        //构造请求参数
//        CommonRequest request = new CommonRequest();
//        request.setSysMethod(MethodType.POST);
//        request.setSysDomain("dysmsapi.aliyuncs.com");
//        request.setSysVersion("2017-05-25");
//        request.setSysAction("SendSms");
//        request.putQueryParameter("RegionId", "cn-hangzhou");
//        request.putQueryParameter("PhoneNumbers", phone);
//        request.putQueryParameter("SignName", "传智健康项目");
//        request.putQueryParameter("TemplateCode", "SMS_175060789");
//        request.putQueryParameter("TemplateParam", "	{\"assertCode\":\"" + code + "\"}");
//        try {
//            //发起请求
//            CommonResponse response = acsClient.getCommonResponse(request);
//            log.info("[短信-发送验证码]response:{}", response.getData());
//        } catch (ClientException e) {
//            log.error("[短信-发送验证码]", e);
//        }

    }

    @Override
    public Integer checkValidateCode(String type, String telephone, String code,Integer count) {
        log.info("[校验验证码]code：{}，phone：{}，type：{},count：{}", code, telephone, type, count);

        //从redis取验证码 用key取
        //key的格式 前缀 类型 手机号 不分割
        String redisKey = RedisConst.VALIDATE_CODE_PREFIX + type + ":" + telephone;
        //从redis获取
        String redisCode = (String) redisTemplate.boundValueOps(redisKey).get();
        //如果redis里面有验证码
        if (!StringUtils.isEmpty(redisCode) ) {
            //验证码正确
            if (redisCode.equals(code)) {
                return 2;
            }
            return 1;
        }
        //验证码超时已失效
        return -1;
    }
}